<template>
  <div class="outpatient-manage">
    <div
      style="
        display: flex;
        justify-content: space-between;
        height: 100%;
        width: 100%;
      "
    >
      <div
        style="width: 100%; height: 100%; overflow: auto; padding-right: 16px"
      >
        <!-- 病历 -->
        <outpatient
          :patientId="patientId"
          :patientDetail="patientDetail"
          :fieldList="medicalList?.fieldList || []"
          activeName_1="default"
          :doctorAdvice="medicalList.doctorAdvice"
          style="width: 100%"
          ref="outpatientRef"
          :visitStatus="visitStatus"
          @doctorAdvice="ondoctorAdvice"
        />

        <!-- 查验项目 -->
        <InspectionTable
          :patientId="patientId"
          :onZS="onZS"
          :frequencyOptions="frequency"
          :patientDetail="patientDetail"
          :tableData="medicalList?.examList || []"
          style="margin-top: 10px"
          :visitStatus="visitStatus"
          ref="inspectionTableRef"
        />
        <!-- 处方医嘱  模板 -->
        <div class="header-section-1">
          <h3>处方医嘱</h3>
          <div class="action-buttons" v-if="visitStatus != '2'">
            <el-button type="primary" plain @click="setActiveType('1')">
              成药处方
            </el-button>
            <el-button type="primary" plain @click="setActiveType('3')">
              中药处方
            </el-button>
            <el-button type="primary" plain @click="setActiveType('2')">
              输液处方
            </el-button>
            <el-button type="primary" plain @click="setActiveType('4')">
              外治处方
            </el-button>
            <!-- <span style="padding: 0 10px; color: #dcdcdc">|</span> -->
            <div class="line" style="margin-left: 10px"></div>
            <el-button plain @click="onSelectTemplate()"> 选择模板 </el-button>
            <el-button plain @click="onSave('3')"> 存模板 </el-button>
          </div>
        </div>
        <div
          class="prescription-template"
          v-for="(item, index) in medicalList?.rxList || []"
        >
          <div v-if="item.rxType === '1'">
            <!-- 成药处方一 -->
            <prescription
              :prescriptionData="item"
              :frequencyOptions="frequency"
              :weight="medicalList.weight"
              :onZS="onZS"
              ref="prescriptionRef"
              :visitStatus="visitStatus"
              @removeRow="(result: any) => removeRow(result, index)"
            />
          </div>
          <div v-if="item.rxType === '2'">
            <!-- 输液处方四 -->
            <transfusion
              :onZS="onZS"
              :weight="medicalList.weight"
              :group="item"
              :visitStatus="visitStatus"
              @addNewRow="(result: any) => addNewRow(result, index)"
              @removeRow="(result: any) => removeRow(result, index)"
              ref="transfusionRef"
            />
          </div>
          <div v-if="item.rxType === '3'">
            <!-- 中药处方二 -->
            <medicinalHerb
              :medicinalHerbData="item"
              :visitStatus="visitStatus"
              ref="medicinalHerbRef"
              @removeRow="(result: any) => removeRow(result, index)"
            ></medicinalHerb>
          </div>
          <div v-if="item.rxType === '4'">
            <!-- 外治处方三 -->
            <ExternalTreatment
              ref="externalTreatmentRef"
              :onZS="onZS"
              :visitStatus="visitStatus"
              :externalTreatment="item"
              @removeRow="(result: any) => removeRow(result, index)"
            ></ExternalTreatment>
          </div>
        </div>
        <div class="followup-box">
          <div class="followup-row">
            <div class="followup-label">是否随访</div>
            <div class="followup-content" v-if="visitStatus != '2'">
              <div class="visit-options">
                <el-radio-group v-model="medicalList.isFollowUp">
                  <el-radio value="0" size="large">不随访</el-radio>
                  <el-radio value="1" size="large">随访</el-radio>
                </el-radio-group>
                <el-input-number
                  v-model="medicalList.followUpDays"
                  placeholder="请输入"
                  class="search-input"
                  clearable
                  :controls="false"
                  style="width: 100px; margin-left: 20px"
                >
                </el-input-number>
                天后随访
              </div>
            </div>
            <div v-else class="followup-content">
              <span v-if="medicalList.isFollowUp == '0'">不随访</span>
              <span v-else>随访</span>
              {{ medicalList.followUpDays }}
              <span v-if="medicalList.isFollowUp == '1'">天后随访</span>
            </div>
          </div>
          <div class="followup-row">
            <div class="followup-label">医嘱事项</div>
            <div class="followup-content">
              <div class="advice-input">
                <DoctorAdviceSelect
                  v-model="medicalList.doctorAdvice"
                  :multi-line="true"
                  :toggle-selected="true"
                  v-if="visitStatus != '2'"
                />
                <span
                  v-else
                  v-html="
                    medicalList.doctorAdvice
                      ? medicalList.doctorAdvice.replace(/\n/g, '<br>')
                      : ''
                  "
                ></span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div>
        <!-- <member-card :patientId="patientId" :historyList="followupRecordList" /> -->
      </div>
      <!-- 选择模板 -->
      <el-dialog
        v-model="isTemplate"
        class="custom-transition-dialog-2"
        :title="''"
        :width="1500"
        top="5vh"
        @close="isTemplate = false"
      >
        <template
          #header="{ close, titleId, titleClass }"
          style="display: none"
        >
          <div class="my-header" style="display: none">
            <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
          </div>
        </template>
        <!-- 1是病历模板 2是检验模板 3是处方模板 -->
        <managePages
          :medicalList="[]"
          @updataTemplate="updataTemplate"
          :activeName_s="'3'"
        />
      </el-dialog>
      <!-- 保存模板 -->
      <addTemplate
        ref="addTemplateRef"
        @addTemplate="onAddTemplate"
      ></addTemplate>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import DoctorAdviceSelect from '@/components/DoctorAdviceSelect.vue';
import emptyImage from '@/assets/icon/internet_empty_illustration.svg';
import { v4 as uuidv4 } from 'uuid';
import medicalRecordPrint from './medicalRecordPrint.vue';
import PatentMedicinePrint from './PatentMedicinePrint.vue';
import inspectPrint from './inspectPrint.vue';
import userSelect from './userSelect.vue';
import dayjs from 'dayjs';
import {
  getMedicalList,
  getFollowupList,
  getFollowupRecordList,
  getMedicalDetail,
  completePreDiagnosis,
  completeInquiry,
  drugConflictCheck,
  getFollowupDetail,
  updateMedicalRecord,
  completeFollowup,
  printMedicalRecord,
  printExam,
  printPrescription,
} from '@/api/medical';
import { CaretBottom, WarningFilled } from '@element-plus/icons-vue';
import PatientUser from './patientUser.vue';
import { CircleCloseFilled } from '@element-plus/icons-vue';
import MemberCard from './memberCard.vue';
import addTemplate from './addTemplate.vue';
import patientUpdata from './PatentMedicinePrint.vue';
import managePages from './managePages.vue';
import patientInfo from './patientInfo.vue';
import outpatient from './outpatient.vue';
import InspectionTable from './InspectionTable.vue';
import medicinalHerb from './medicinalHerb.vue';
import ExternalTreatment from './ExternalTreatment.vue';
import flollowRecording from './flollowRecording.vue';
import transfusion from './transfusion.vue';
import prescription from './prescription.vue';
import { getDeliveryHistoryList, getDispenseHistoryList } from '@/api/pharmacy';
import {
  getPatientList,
  getPatientDetail,
  getPatientMedicalField,
} from '@/api/patient';
import type {
  PatientInfo,
  PatientDetail,
  RechargeOrderListData,
  RechargeOrderQueryParams,
} from '@/types/patient';
import FollowUpForm from './followUpForm.vue';
import store from '@/store';
import {
  addTemplateMedical,
  addTemplatePrescription,
  addTemplateInspection,
} from '@/api/formwork';
const useBaseDataStores = store.useBaseDataStore();
const storageList = ref<any[]>(useBaseDataStores.Storage);
const formData = ref<any>({
  visitDate: dayjs(new Date()).format('YYYY-MM-DD'),
});
const frequency = ref(useBaseDataStores.getDictsSelect('FREQUENCY'));
const medicalFieldStore = store.useMedicalRecordFieldStore();
const isPlusSign = ref(false); // 是否显示草稿患者
// const patientUpdataRef = ref<InstanceType<typeof patientUpdata>>();
const followUpFormRef = ref<InstanceType<typeof FollowUpForm>>();
const addTemplateRef = ref<InstanceType<typeof addTemplate> | null>(null);
const userSelectDom = ref<InstanceType<typeof userSelect> | null>(null);
const patientList = ref<any[]>([]); // 患者列表
const followupList = ref<any[]>([]); // 随访列表
const MedicalPrintinfo = ref<any>({}); //病历打印数据
const inspectPrintInfo = ref<any>({}); //检验打印数据
const PrescriptionPrintInfo = ref<any>({}); //处方打印数据
const CustomDatePickerShow = ref(false);
const activeTab = ref('execute'); // tab状态
const templateDialog = ref(false); // 病历模板弹窗
const followupId = ref<number | null>(null); // 当前选中的随访ID
const visiblePrint = ref(false);
const medicalRecordPrintRef = ref<InstanceType<
  typeof medicalRecordPrint
> | null>(null);
const inspectPrintRef = ref<InstanceType<typeof inspectPrint> | null>(null);
const PatentMedicinePrintRef = ref<InstanceType<
  typeof PatentMedicinePrint
> | null>(null);
const ZSValue = ref(''); // 主诉
// 搜索和筛选
const patientName = ref('');
const selectedDate = ref('today');
const patientDetail = ref<PatientDetail | undefined>(undefined); // 当前选中的患者详情
const followDetail = ref<any>({}); // 随访详情
const medicalList = ref<any>({
  isFollowUp: '1',
}); //病历详情
const isTemplate = ref(false); // 选择模板弹窗
const isMedical = ref(false); // 保存模板弹窗
const visitStatus = ref('');
// 风险提示列表（可由后端校验结果赋值，支持富文本片段）
const riskList = ref<string[]>([]);
const followList = ref<any[]>([]); // 随访列表
const pageNo = ref(1);
const pageSize = ref(10);
const dispenseHistoryList = ref<any[]>([]);
const callDialog = ref<boolean>(false);
const patientId = ref<number | null>(null); // 当前选中的患者ID
const outpatientRef = ref<InstanceType<typeof outpatient>>(); // 病历的ref获取病历模板数据
const inspectionTableRef = ref<InstanceType<typeof InspectionTable>>(); // 检验项目的ref获取检验项目数据
// 这些组件在 v-for 中使用了相同的 template ref 名称，Vue 会将它们收集为“数组模板引用”
const prescriptionRef = ref<InstanceType<typeof prescription>[]>([]); // 处方（数组）
const transfusionRef = ref<InstanceType<typeof transfusion>[]>([]); // 输液（数组）
const medicinalHerbRef = ref<InstanceType<typeof medicinalHerb>[]>([]); // 中药（数组）
const externalTreatmentRef = ref<InstanceType<typeof ExternalTreatment>[]>([]); // 外治处方（数组）
const medicalId = ref<number | null>(null); // 当前选中的病历ID
const handleClick = (tab: any, event: Event) => {
  //console.log(tab, event);
};
const form = ref({
  name: '',
  gender: '男',
  age: '',
  month: '',
  weight: '',
  bloodPressure: '',
});
const followupRecordList = ref<any[]>([]); // 随访记录列表
const onUserInfo = async (id: any, medical: any, visitStatus1: any) => {
  // 这里可以添加跳转到患者详情页面的逻辑
  patientId.value = id; // 设置当前选中的患者ID
  medicalId.value = medical;
  isPlusSign.value = false;
  if (visitStatus1 == '1') {
    visitStatus.value = '1';
  } else {
    visitStatus.value = '2';
  }

  // 获取患者详情
  const data = await getPatientDetail({ patientId: id });
  patientDetail.value = data.data; // 更新患者详情
  getMedicalDetailData(); // 获取病历详情
};
const formatDate = (date: Date) => {
  return dayjs(date).format('YYYY-MM-DD');
};
const CustomDatePickerChange = (date: any) => {
  // 为空直接关闭
  if (!date) {
    CustomDatePickerShow.value = false;
    return;
  }

  // 规范化为 YYYY-MM-DD 字符串
  const next = dayjs(date).isValid()
    ? dayjs(date).format('YYYY-MM-DD')
    : String(date);
  formData.value.visitDate = next;
  if (activeTab.value === 'execute') {
    getMedicalListData();
  } else {
    getFollowupListData();
  }
  patientId.value = null;
  CustomDatePickerShow.value = false;
};
const onFollowup = async (id: any, patientId1: any) => {
  followupId.value = id; // 获取患者ID
  patientId.value = patientId1; // 设置当前选中的患者ID
  followupRecord(); // 获取患者随访记录
  followupRecordDdta();
};
// 获取患者随访记录
const followupRecordDdta = async () => {
  const data = await getFollowupDetail({
    followupId: followupId.value,
  });
  if (data.code != '200') {
    //ElMessage.error(data.msg);
    return;
  }
  followDetail.value = data.data;
};
const onActivated = async (value: string) => {
  activeTab.value = value;
  patientId.value = null;
  if (value === 'execute') {
    getMedicalListData();
  } else {
    getFollowupListData();
  }
};
const onEdit = () => {
  visitStatus.value = '1';
};
// 数字改成中文
const toChineseNumber = (num: number) => {
  const cnNums = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  const cnUnits = ['', '十', '百', '千', '万'];
  if (num < 10) return cnNums[num];
  if (num < 20) return '十' + (num === 10 ? '' : cnNums[num % 10]);
  if (num < 100) {
    const ten = Math.floor(num / 10);
    const unit = num % 10;
    return cnNums[ten] + '十' + (unit === 0 ? '' : cnNums[unit]);
  }
  // 这里只处理到99，更多位数可扩展
  return num;
};

const props = defineProps<{
  medicalRecordList?: any;
}>();
watch(
  () => props.medicalRecordList,
  (val) => {
    medicalList.value = val;
    visitStatus.value = '2';
  },
  { immediate: true, deep: true }
);
// 添加处方
const addNewRow = (group?: any, index?: any) => {
  const num = index + 1;
  //console.log(group);

  const data = {
    groupList: [
      {
        groupName: '第一组',
        usageCode: 'JMDZ',
        usageCodeText: '静脉滴注',
        frequencyCode: 'qd',
        frequencyCodeText: '1天1次',
        frequencyTimes: 1,
        cycle: 1,
        cycleUnit: 'day',
        cycleUnitText: '天',
        ivDripRate: '50',
        subtotal: 1000,
        uuid: uuidv4(),
        detailList: [],
      },
    ],
    rxType: '2',
    rxName: '输注处方' + toChineseNumber(num),
    totalAmount: 0,
    uuid: uuidv4(), // 唯一标识
    storageId: storageList.value.find((item) => item.isDefault == 1)?.storageId,
  };
  medicalList.value.rxList = (medicalList.value.rxList || []).concat(data);
  ElMessage.success('添加成功');
};
// 删除处方
const removeRow = (group?: any, index?: any) => {
  medicalList.value.rxList.splice(index, 1);
  ElMessage.success('处方已删除');
};
const today = computed(() => {
  const date = new Date();
  return date.toISOString().split('T')[0]; // YYYY-MM-DD格式
});
// 获取病历详情
const getMedicalDetailData = async () => {
  if (patientId.value) {
    const data = await getMedicalDetail({ medicalId: medicalId.value });
    if (data.code != '200') {
      //ElMessage.error(data.msg);
      return;
    }
    data.data.rxList.forEach((element: { uuid: string }) => {
      element.uuid = uuidv4(); // 为每个处方生成唯一标识符
    });
    medicalList.value = data.data;
    // 修改血压值的赋值逻辑，增加空值判断
    medicalList.value.systolicName =
      (medicalList.value.systolicBp ? medicalList.value.systolicBp : '') +
      '/' +
      (medicalList.value.diastolicBp ? medicalList.value.diastolicBp : '');
    //console.log(medicalList.value);
  }
};
// 接诊
const onPlusSign = async () => {
  // x选择患者弹窗
  isPlusSign.value = true;
  const data = {
    patientName: '',
    pageNo: 1,
    pageSize: 1000000,
  };
  patientId.value = 99999;
  medicalId.value = 99999;
  medicalList.value.visitStatus = '1';
  visitStatus.value = '1';
  medicalList.value.fieldList = [];
  medicalList.value.examList = [];
  medicalList.value.rxList = [];
  medicalList.value.isFollowUp = '0';
  medicalList.value.doctorAdvice = '';
  medicalList.value.followUpDays = null;
  medicalList.value.ageYear = null;
  medicalList.value.patientName = '';
  medicalList.value.patientGender = '';
  medicalList.value.weight = null;
  medicalList.value.systolicName = '';
  medicalList.value.ageMonth = null;
  medicalList.value.diastolicBp = null;

  // const response = await getPatientList(data);
  // if (response && response.data) {
  //   // patientList.value = response.data;
  //   activeTab.value = 'execute';
  //   userSelectDom.value?.open(response.data);
  // }
};

const tomorrow = computed(() => {
  const date = new Date();
  date.setDate(date.getDate() + 1);
  return date.toISOString().split('T')[0];
});

const onToolboxs = () => {
  //console.log('叫号');
  callDialog.value = true;
  // 打开叫号弹窗的逻辑
  // 这里可以添加打开叫号弹窗的代码
};
// 保存模板
const onAddTemplate = async (data: any) => {
  // //console.log('保存模板数据:', data);
  //   const examList= fields.value.map((item: { fieldId: any; fieldValue: any; fieldImages: any;})=>{
  //   return {
  //     fieldId: item.fieldId,
  //     fieldValue: item.fieldValue,
  //     fieldImages: item.fieldImages,
  //   }
  // })
  // const data1 = {
  //   ...data,
  //   recomScene: '',
  //   fieldList: examList,
  // }
  // const result = await addTemplateMedical(data1);
  const data2 = dataProcess();
  if (data.templateCategory == '2') {
    const data1 = {
      ...data,
      templateCategory: data.templateType,
      templateType: data.templateType,
      examList: data2.examList,
    };
    const result = await addTemplateInspection(data1);
    if (result.code != '200') {
      //ElMessage.error(result.msg);
      return;
    }
  }
  if (data.templateCategory == '3') {
    const data1 = {
      ...data,
      templateCategory: data.templateType,
      templateType: data.templateType,
      rxList: data2.rxList,
    };
    const result = await addTemplatePrescription(data1);
    if (result.code != '200') {
      //ElMessage.error(result.msg);
      return;
    }
  }
   if (addTemplateRef.value && typeof addTemplateRef.value.onclose === 'function') {
  addTemplateRef.value.onclose();
}
  ElMessage.success('模板保存成功');
};

const formattedVisitDate = computed(() => {
  const val = formData.value.visitDate;
  if (!val) return '';
  const current = dayjs();
  const target = dayjs(val);
  if (!target.isValid()) return '';
  return target.isSame(current, 'day') ? '今天' : target.format('MM-DD');
});

// 选择模板
const onSelectTemplate = () => {
  isTemplate.value = true;
};
const yesterday = computed(() => {
  const date = new Date();
  date.setDate(date.getDate() - 1);
  return date.toISOString().split('T')[0];
});
// 设置处方类型
// 方法
const setActiveType = (type: string) => {
  // activeType.value = type;
  // 构造不同类型的处方对象
  // 统计同类型数量

  const sameTypeCount =
    medicalList.value?.rxList?.filter(
      (i: { rxType: string }) => i.rxType === type
    ).length || 0;
  let newRx: any = {
    rxType: type,
    rxName: '',
    payStatus: null,
    payTime: null,
    storageId: storageList.value.find((item) => item.isDefault == 1)?.storageId,
    totalAmount: null,
    uuid: uuidv4(), // 唯一标识
  };
  switch (type) {
    case '1':
      newRx.rxName = `中西成药处方${toChineseNumber(sameTypeCount + 1)}`;
      //console.log(newRx.rxName);

      newRx.detailList = [];
      break;
    case '2':
      newRx.rxName = `输注处方${toChineseNumber(sameTypeCount + 1)}`;
      newRx.groupList = [
        {
          groupName: '第一组',
          usageCode: 'JMDZ',
          usageCodeText: '静脉滴注',
          frequencyCode: 'qd',
          frequencyCodeText: '1天1次',
          frequencyTimes: 1,
          cycle: 1,
          cycleUnit: 'day',
          cycleUnitText: '天',
          ivDripRate: '50',
          subtotal: 1000,
          uuid: uuidv4(),
          detailList: [],
        },
      ];
      break;
    case '3':
      newRx.rxName = `中药处方${toChineseNumber(sameTypeCount + 1)}`;
      newRx.tcmInfo = {
        frequencyCode: 'bid',
        frequencyCodeText: '1天2次',
        dailyDosage: '1',
        cycle: 7,
        cycleUnit: 'day',
        cycleUnitText: '天',
        usageCode: 'JFU',
        usageCodeText: '煎服',
        singleDosage: '200',
        remark: '',
        totalDoses: 0,
        subtotal: 0,
        detailList: [],
        uuid: uuidv4(), // 唯一标识
      };
      break;
    case '4':
      newRx.rxName = `外治处方${toChineseNumber(sameTypeCount + 1)}`;
      newRx.extInfo = {
        projectId: '',
        projectName: '',
        projectCategory: '',
        price: 0,
        projectType: '',
        frequencyCode: 'qd',
        frequencyCodeText: '1天1次',
        cycle: 1,
        cycleUnit: 'day',
        cycleUnitText: '天',
        remark: '',
        totalOutQty: '',
        totalOutQtyUnit: '',
        totalOutQtyUnitText: '',
        subtotal: '',
        detailList: [],
        uuid: uuidv4(), // 唯一标识
      };
      newRx.detailList = [];
      break;
  }
  medicalList.value?.rxList.push(newRx);
  //console.log(medicalList.value?.rxList);
};
const onSave = (value: string) => {
  if (medicalList.value?.rxList?.length == 0) {
    //ElMessage.error('请先添加处方');
    return;
  }
  const type = {
    templateCategory: value,
    templateType: '1',
  };
  addTemplateRef.value?.open1(type);
};
//选择时间
const handleSearch = () => {
  if (selectedDate.value == 'today') {
    formData.value.visitDate = today.value;
  } else if (selectedDate.value == 'tomorrow') {
    formData.value.visitDate = tomorrow.value;
  } else if (selectedDate.value == 'yesterday') {
    formData.value.visitDate = yesterday.value;
  }
  formData.value.patientName = patientName.value;
  if (activeTab.value == 'follow') {
    getFollowupListData();
  } else {
    getMedicalListData();
  }
};
// 取消
const onCancel = () => {
  // isTemplate.value = false;
};
// 随访记录
const followupRecord = async () => {
  const params = {
    patientId: patientId.value,
    pageNo: 1,
    pageSize: 10000,
  };
  const response = await getFollowupRecordList(params);
  if (response.code == '200') {
    followupRecordList.value = response.data;
  }
};
const updataTemplate = (templates: any) => {
  //console.log(templates);
  templates.rxList.forEach((item: any) => {
    item.uuid = uuidv4();
    item.storageId = storageList.value.find(
      (item) => item.isDefault == 1
    )?.storageId;
  });
  isTemplate.value = false;
  medicalList.value.rxList = [...medicalList.value.rxList, ...templates.rxList];

  // displayTableData.value = templates.detailList.map(
  //   (item: {
  //     projectCategory: string;
  //     price: number;
  //     subtotal: number;
  //     cycleUnit: string;
  //     totalOutQtyUnit: string;
  //   }) => ({
  //     ...item,
  //     projectCategoryName: useBaseDataStore.getEnumData(
  //       item.projectCategory,
  //       'projectCategoryEnum'
  //     ),
  //     priceNum: '￥' + (item.price / 100).toFixed(2), // 保留两位小数
  //     subtotalNum: '￥' + (item.subtotal / 100).toFixed(2),
  //     cycleUnitText: useBaseDataStore.getEnumData(
  //       item.cycleUnit,
  //       'cycleUnitEnum'
  //     ),
  //     totalOutQtyUnitText: useBaseDataStore.getDictsData(
  //       item.totalOutQtyUnit,
  //       'UNIT'
  //     ),
  //   })
  // );
};
const ondoctorAdvice = (value: any) => {
  medicalList.value.doctorAdvice = value;
};
onMounted(async () => {
  try {
    // const response = await getPatientList();
    // if (response && response.data) {
    //   patientList.value = response.data;
    //   if (patientList.value.length > 0) {
    //     patientId.value = patientList?.value[0]?.patientId || null; // 默认选中第一个患者
    //     onUserInfo(patientId.value);
    //   }
    // }
    // //console.log('患者列表:', response);
    formData.value.visitDate = dayjs().format('YYYY-MM-DD');
    //console.log(today.value);
    // 如果数据还没有加载，则加载医疗记录字段数据
    if (!medicalFieldStore.isDataLoaded) {
      try {
        await medicalFieldStore.fetchMedicalRecordFields();
      } catch (error) {
        //console.error('加载医疗记录字段失败:', error);
        //ElMessage.error('加载医疗记录字段失败');
      }
    }
  } catch (error) {
    //console.error('获取患者列表失败:', error);
  }
});

const getDispenseHistoryListApi = async (patientId: number) => {
  if (activeTab.value == 'dispense') {
    const res = await getDispenseHistoryList({
      patientId,
      pageNo: 1,
      pageSize: 10000,
    });

    if (res.code == '200') {
      dispenseHistoryList.value = res.data || [];
    } else {
      
    }
  } else {
    const res = await getDeliveryHistoryList({
      patientId,
      pageNo: 1,
      pageSize: 10000,
    });

    if (res.code == '200') {
      dispenseHistoryList.value = res.data || [];
    } else {
      
    }
  }
};
const onPatientAdd = () => {
  //console.log('添加新患者');
  // patientUpdataRef.value?.open(); // 打开添加患者的弹窗
  // 这里可以添加跳转到添加患者页面的逻辑
};
// 随访列表
const getFollowupListData = async () => {
  const data = {
    pageNo: 1,
    pageSize: 10000,
    followupDate: formData.value.visitDate,
  };
  const res = await getFollowupList(data);
  if (res.code == '200') {
    patientId.value = null;
    followupList.value = res.data;
    followupId.value = null;
    //console.log('随访列表:', res.data);
  } else {
    
  }
};
const printBox = () => {
  medicalRecordPrintRef.value?.getHtml();
};
const printBox1 = () => {
  inspectPrintRef.value?.getHtml();
};
const onPrint = async () => {
  const data1 = await printMedicalRecord({ medicalId: medicalId.value });
  if (data1.code != '200') {
   
    return;
  }
  MedicalPrintinfo.value = data1.data;
  const data2 = await printExam({ medicalId: medicalId.value });
  if (data2.code != '200') {
    
    return;
  }
  inspectPrintInfo.value = data2.data;
  const data3 = await printPrescription({ medicalId: medicalId.value });
  if (data3.code != '200') {
    
    return;
  }
  PrescriptionPrintInfo.value = data3.data;
  visiblePrint.value = true;
  medicalRecordPrintRef.value?.onPrintQRCode();
  inspectPrintRef.value?.onPrintQRCode();
};
// 格式化数据（仅返回指定精简字段）
const dataProcess = () => {
  const base = medicalList.value || {};
  const safeMap = (arr: any, fn: (x: any) => any) =>
    Array.isArray(arr) ? arr.map(fn) : [];

  // 规范化图片字段：数组/字符串 -> 标准化后的逗号分隔字符串
  const normalizeImages = (val: any): string => {
    if (Array.isArray(val))
      return val
        .map((s) => String(s).trim())
        .filter(Boolean)
        .join(',');
    if (typeof val === 'string')
      return val
        .split(',')
        .map((s) => s.trim())
        .filter((s) => !!s)
        .join(',');
    return '';
  };

  // 1) 病历字段最小化
  const fieldList = safeMap(outpatientRef.value?.fields, (f: any) => ({
    fieldId: f.fieldId,
    fieldValue: f.fieldValue,
    fieldImages: normalizeImages(f.fieldImages),
  }));

  // 2) 查验项目最小化
  const examList = safeMap(
    inspectionTableRef.value?.displayTableData,
    (it: any) => ({
      projectId: it.projectId,
      frequencyCode: it.frequencyCode,
      examId: it.examId || null,
      cycle: it.cycle,
      remark: it.remark,
      totalOutQty: it.totalOutQty,
    })
  );

  // 3) 处方/医嘱最小化（按 rxType 归一，优先取各子组件最新状态，通过 uuid 匹配）
  const findByUuid = <T>(
    list: T[] | undefined,
    pick: (x: T) => any,
    uuid: any
  ) => {
    if (!Array.isArray(list)) return undefined;
    return list.find((inst: any) => pick(inst)?.uuid === uuid);
  };

  const rxList = safeMap(base.rxList, (rx: any) => {
    const rxType = String(rx?.rxType || '');
    const uuid = rx?.uuid;
    let src: any = rx; // 兜底：使用 medicalList 中的对象
    //console.log(src, 'srcsrcsrcsrcsrc');

    if (rxType === '1') {
      const inst = findByUuid(
        prescriptionRef.value,
        (c: any) => c?.displayNow,
        uuid
      );
      if (inst?.displayNow) src = inst.displayNow;
      return {
        storageId: src.storageId ?? null,
        rxName: src.rxName,
        rxType: '1',
        rxId: src.rxId || null,
        detailList: safeMap(src.detailList, (d: any) => ({
          drugId: d.drugId,
          usageCode: d.usageCode,
          frequencyCode: d.frequencyCode,
          dosage: d.dosage,
          cycle: d.cycle,
          remark: d.remark,
          totalOutQty: d.totalOutQty,
        })),
      };
    }
    if (rxType === '2') {
      const inst = findByUuid(
        transfusionRef.value,
        (c: any) => c?.transfusionTableData,
        uuid
      );
      //console.log(inst, '输液处方实例');

      if (inst?.transfusionTableData) src = inst.transfusionTableData;
      return {
        storageId: src.storageId ?? null,
        rxName: src.rxName,
        rxId: src.rxId || null,
        rxType: '2',
        groupList: safeMap(src.groupList, (g: any) => ({
          groupName: g.groupName,
          usageCode: g.usageCode,
          frequencyCode: g.frequencyCode,
          cycle: g.cycle,
          ivDripRate: g.ivDripRate,
          detailList: safeMap(g.detailList, (d: any) => ({
            drugId: d.drugId,
            dosage: d.dosage,
            skinTest: d.skinTest,
            remark: d.remark,
            totalOutQty: d.totalOutQty,
          })),
        })),
      };
    }
    if (rxType === '3') {
      const inst = findByUuid(
        medicinalHerbRef.value,
        (c: any) => c?.externalTreatment,
        uuid
      );
      if (inst?.externalTreatment) src = inst.externalTreatment;
      return {
        storageId: src.storageId ?? null,
        rxName: src.rxName,
        rxId: src.rxId || null,
        rxType: '3',
        tcmInfo: {
          usageCode: src.tcmInfo?.usageCode,
          frequencyCode: src.tcmInfo?.frequencyCode,
          cycle: src.tcmInfo?.cycle,
          dailyDosage: src.tcmInfo?.dailyDosage,
          singleDosage: src.tcmInfo?.singleDosage,
          remark: src.tcmInfo?.remark,
          detailList: safeMap(src.tcmInfo?.detailList, (d: any) => ({
            drugId: d.drugId,
            dosage: d.dosage,
            decotionMethod: d.usageCode,
          })),
        },
      };
    }
    if (rxType === '4') {
      const inst = findByUuid(
        externalTreatmentRef.value,
        (c: any) => c?.externalTreatment,
        uuid
      );
      if (inst?.externalTreatment) src = inst.externalTreatment;
      return {
        rxName: src.rxName,
        rxId: src.rxId || null,
        rxType: '4',
        extInfo: {
          projectId: src.extInfo?.projectId,
          frequencyCode: src.extInfo?.frequencyCode,
          cycle: src.extInfo?.cycle,
          remark: src.extInfo?.remark,
          detailList: safeMap(src.extInfo?.detailList, (d: any) => ({
            acupointCode: d.acupointCode,
            sideType: d.sideType,
          })),
        },
      };
    }
    return null;
  }).filter(Boolean);

  // 4) 顶层患者字段（仅保留指定项）
  const systolicName = base.systolicName || '';
  const [sysFromName, diaFromName] = String(systolicName).split('/') as [
    string,
    string
  ];

  const data1: any = {
    medicalId: base.medicalId ?? medicalId.value ?? null,
    patientName: base.patientName ?? patientDetail.value?.patientName ?? '',
    patientPhone: base.patientPhone ?? patientDetail.value?.patientPhone ?? '',
    weight: base.weight ?? '',
    systolicBp: base.systolicBp ?? sysFromName ?? '',
    diastolicBp: base.diastolicBp ?? diaFromName ?? '',
    patientGender:
      base.patientGender ?? patientDetail.value?.patientGender ?? '',
    idCard: base.idCard ?? patientDetail.value?.idCard ?? '',
    isFollowUp: base.isFollowUp ?? '1',
    followUpDays: base.followUpDays ?? undefined,
    doctorAdvice: base.doctorAdvice ?? '',
    fieldList,
    patientId: patientId.value,
    examList,
    rxList,
  };
  if (data1.medicalId == 99999) {
    delete data1.medicalId;
  }
  //console.log(data1, '最终数据');
  return data1;
};
// 获取主诉
const onZS = (value: string) => {
  medicalList.value.mainComplaint = value;
  ZSValue.value = outpatientRef.value?.fields.find(
    (f: any) => f.fieldCode === 'ZS'
  )?.fieldValue;
  return ZSValue.value;
};
// 完成预诊
const onCompletePreDiagnosis = async () => {
  //console.log('完成预诊');
  //console.log(medicalList.value);
  isPlusSign.value = false;
  //console.log(outpatientRef.value?.fields); //获取病历模板数据
  //console.log(inspectionTableRef.value?.displayTableData); //获取检验项目数据
  //console.log(prescriptionRef.value); // 获取处方数据（数组）
  //console.log(transfusionRef.value?.[0]?.transfusionTableData); // 获取输液处方数据（首个实例）
  //console.log(medicinalHerbRef.value?.[0]?.externalTreatment, '中药处方'); // 获取中药处方数据（首个实例）
  //console.log(externalTreatmentRef.value?.[0]?.externalTreatment, '外治处方'); // 获取外治处方数据（首个实例）
  const data = dataProcess();
  const res = await completePreDiagnosis(data);
  if (res.code == '200') {
    ElMessage.success('预诊完成');
    getMedicalListData();
  } else {

  }
  //console.log(res);
};
// 编辑门诊
const onCompletePreDiagnosisEdit = async () => {
  //console.log('编辑门诊');
  let data = dataProcess();
  data.medicalId = medicalId.value;
  const res = await updateMedicalRecord(data);
  if (res.code == '200') {
    ElMessage.success('门诊信息更新成功');
    visitStatus.value = '2';
    getMedicalDetailData();
  } else {

  }
};
const handleSelect1 = (obj: any) => {
  patientId.value = obj.patientId;
  medicalList.value.ageYear = obj.ageYear;
  medicalList.value.ageMonth = obj.ageMonth;
  medicalList.value.patientGender = obj.patientGender;
  medicalList.value.patientName = obj.patientName;
  medicalList.value.idCard = obj.idCard;
  medicalList.value.patientPhone = obj.patientPhone;
  medicalList.value.weight = obj.weight;
  medicalList.value.patientId = obj.patientId;
  medicalList.value.systolicName =
    (obj.systolicBp ? obj.systolicBp : '') +
    '/' +
    (obj.diastolicBp ? obj.diastolicBp : '');
};
const onReceivingPatients = async () => {
  //console.log('完成接诊');

  const data = dataProcess();
  const res = await drugConflictCheck(data);
  if (res.code == '200') {
    isPlusSign.value = false;
    if (res.data.length > 0) {
      isMedical.value = true;
    } else {
      isMedical.value = false;
      handleSubmit();
    }
    riskList.value = res.data;

    // ElMessage.success('接诊完成');
    // isMedical.value = false;
    // getMedicalListData();
  } else {

  }
};
const handleSubmit = async () => {
  //console.log('继续提交');
  const data = dataProcess();
  const res = await completeInquiry(data);
  if (res.code == '200') {
    ElMessage.success('接诊完成');
    isMedical.value = false;
    getMedicalListData();
  } else {

  }
};
// 获取患者列表
const getMedicalListData = async () => {
  const res = await getMedicalList({
    pageNo: 1,
    pageSize: 10000,
    ...formData.value,
  });
  if (res.code == '200') {
    patientList.value = res.data;
    patientId.value = null;
    medicalId.value = null;
    //console.log('诊室列表:', res.data);
  } else {

  }
};
</script>

<style scoped lang="scss">
.outpatient-manage {
}
::v-deep(.el-input__wrapper) {
  padding-left: 5px !important;
  padding-right: 5px !important;
}
.register-date-custom-picker {
  position: absolute;
  top: 33px;
  z-index: 10;
  background: #fff;
  box-shadow: 0px 5px 5px -3px rgba(0, 0, 0, 0.1),
    0px 8px 10px 1px rgba(0, 0, 0, 0.06), 0px 3px 14px 2px rgba(0, 0, 0, 0.05);
  width: 100%;
}
.line {
  width: 0px;
  height: 23px;
  border: 1px solid #dcdcdc;
  margin-right: 10px;
}
// ::v-deep(.custom-transition-dialog-2) {
//   padding: 0 !important;
//   .el-dialog__header {
//     padding: 0 !important;
//   }
// }
::v-deep(.custom-transition-dialog-2) {
  padding: 0 !important;
}
::v-deep(.custom-transition-dialog-2 > .el-dialog__header) {
  padding: 0 !important;
}
.risk-dialog-body {
  padding: 12px 16px 4px 16px;
  max-height: 50vh;
  overflow: auto;
}
.risk-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  color: #d93026; /* 红色提示 */
  font-size: 14px;
  line-height: 22px;
  padding: 6px 0;
  border-bottom: 1px solid #eee;
}

.risk-icon {
  color: #d93026;
  font-size: 18px;
  margin-top: 2px;
}
.risk-text {
  flex: 1;
}
.risk-empty {
  color: rgba(0, 0, 0, 0.45);
  text-align: center;
  padding: 16px 0;
}
.search-container-box {
  height: calc(100% - 233px);
  overflow: auto;
}
.patient-container {
  padding: 10px;
  height: calc(100% - 55px);
  overflow: auto;
  .search-container {
    display: flex;
    gap: 7px;
    align-items: center;
    margin-bottom: 10px;
    position: relative;

    .search-input {
      flex: 1;
      width: 182px;
    }
    .date-select {
      width: 48px;
    }
  }
}

.patient-header {
  display: flex;
  align-items: center;
  position: relative;
  width: 100%;
  padding: 10px;
  border-bottom: 1px solid #e7e7e7;

  .patient-title {
    font-size: 18px;
    font-weight: 600;
    color: var(--el-color-primary);
  }

  .patient-line {
    position: absolute;
    width: 30px;
    top: 41px;
    height: 2px;
    background-color: var(--el-color-primary);
    margin-top: 4px;
  }
}
.user-info-container {
  background-color: #f0f0f0;
  padding: 10px;
}
.user-info-active {
  background: rgba(24, 179, 171, 0.1);
  border-radius: 6px 6px 6px 6px;
  border: 1px solid var(--el-color-primary);
}
.user-info—box {
  padding: 10px;
}
.user-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-radius: 5px;
  cursor: pointer;
  .user-info.selected {
    background-color: #bce8f1;
  }

  .avatar {
    width: 16px;
    height: 16px;
  }

  .name {
    font-size: 15px;
  }

  .dropdown-icon {
    margin-left: auto;
  }

  .phone-number {
    font-family: Microsoft YaHei, Microsoft YaHei;
    font-weight: 400;
    font-size: 13px;
    color: rgba(0, 0, 0, 0.4);
    line-height: 22px;
    text-align: left;
    font-style: normal;
    text-transform: none;
    // margin-left: 10px;
  }

  .age {
    font-family: Microsoft YaHei, Microsoft YaHei;
    font-weight: 400;
    font-size: 14px;
    color: rgba(0, 0, 0, 0.4);
  }

  .status-info {
    display: flex;
    align-items: center;
    gap: 4px;
  }

  .status-dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background-color: #ff8c00;
    display: inline-block;
  }

  .status-text {
    font-family: Microsoft YaHei, Microsoft YaHei;
    font-weight: 400;
    font-size: 14px;
    // font-weight: 600;
  }
}
::v-deep(.el-tabs__item) {
  width: 90px !important; /* 设置每个tab的宽度 */
  padding: 0 !important; /* 去除默认padding */
}
.recent-visit {
  padding-bottom: 10px;
  margin: 0 auto;
  text-align: right;
}

.sidebar-tabs {
  flex-shrink: 0;
  display: flex;
  gap: 24px;
  height: 52px;
  padding-left: 22px;
  border: 1px solid #e7e7e7;

  .tab-btn {
    cursor: pointer;
    font-weight: 400;
    font-size: 18px;
    color: rgba(0, 0, 0, 0.4);
    line-height: 52px;
    text-align: left;
    font-style: normal;
    text-transform: none;
    position: relative;

    &.active {
      font-weight: 400;
      font-size: 18px;
      color: #18b3ab;
      text-align: left;
      font-style: normal;
      text-transform: none;

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 3px;
        background: #18b3ab;
      }
    }
  }
}
</style>
<style lang="scss">
.date-select {
  .el-select__wrapper {
    border: none !important;
    box-shadow: none !important;
    background-color: transparent !important;
    padding: 0 !important;
  }

  .el-input__inner {
    color: var(--el-color-primary) !important;
    font-weight: 500 !important;
  }

  // 设置后缀图标颜色为黑色
  .el-icon {
    color: #000 !important;
  }
}
.header-section-1 {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 10px 0px 0 0;
  padding: 12px 20px;
  background: #ffffff;
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
  h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }

  .action-buttons {
    display: flex;
    align-items: center;
    .el-button.active {
      background-color: #409eff;
      color: white;
      border-color: #409eff;
    }
  }
}
.patient-info-bar-1 {
  display: flex;
  align-items: center;
  background: #f8fafb;
  border-radius: 6px;
  box-sizing: border-box;
  justify-content: space-between;
  padding-bottom: 10px;
  position: relative;
}
.patient-info-bar {
  display: flex;
  align-items: center;
  background: white;
  border-radius: 6px;
  padding: 8px 16px;
  box-sizing: border-box;
  .info-input {
    width: 90px;
    margin-right: 0;
    background: transparent;
    .el-input__wrapper {
      background: transparent;
      border: none;
      box-shadow: none;
      padding: 0 8px;
    }
    input {
      background: transparent;
      border: none;
      box-shadow: none;
      font-size: 15px;
      color: #333;
      padding: 0;
    }
  }
  .name-input {
    width: 70px;
  }
  .age-input,
  .month-input {
    width: 60px;
  }
  .weight-input {
    width: 80px;
  }
  .bp-input {
    width: 110px;
  }
  .unit {
    color: #bbb;
    font-size: 15px;
    margin: -2px 4px 0 0;
    color: #000000;
  }
  .divider {
    width: 1px;
    height: 28px;
    background: #e5e6eb;
    margin: 0 20px;
  }
  .gender-group {
    margin: 0 8px 0 0;
    .el-radio-button__inner {
      border: none;
      background: transparent;
      color: #333;
      font-size: 15px;
      padding: 0 12px;
    }
    .el-radio-button__orig-radio:checked + .el-radio-button__inner {
      background: #fff;
      color: #18b3ab;
      border-radius: 4px;
      box-shadow: 0 0 0 1px #18b3ab;
    }
  }
  .btn-group {
    display: flex;
    align-items: center;
    margin-left: 16px;
    gap: 8px;
    .el-button {
      min-width: 90px;
      font-size: 15px;
      border-radius: 4px;
      padding: 0 18px;
    }
    .el-button--primary {
      background: #18b3ab;
      border-color: #18b3ab;
    }
  }
}
</style>

<!-- 复刻“是否随访/医嘱事项”卡片样式 -->
<style lang="scss" scoped>
.printBtn {
  width: 296px;
  cursor: pointer;
  line-height: 46px;
  background: rgba(220, 220, 220, 0.1);
  border-radius: 6px 6px 6px 6px;
  border: 1px solid #ebebeb;
  text-align: center;
  font-weight: 400;
  font-size: 16px;
  color: #16ada4;
}
.printBtn:hover {
  border: 1px solid rgba(22, 173, 164, 0.48);
  background: rgba(22, 173, 164, 0.08);
}
.followup-box {
  background: #fff;
  border: 1px solid #e7e7e7;
  border-radius: 12px;
  // overflow: hidden;
  margin-top: 10px;
  /* 卡片与周围间距按需放开 */
  /* margin-top: 10px; */

  .followup-row {
    display: flex;
    align-items: center;
    min-height: 52px;
    border-bottom: 1px solid #f0f0f0;
    &:last-child {
      border-bottom: none;
    }

    .followup-label {
      width: 110px;
      padding: 0 14px;
      color: #666;
      font-size: 14px;
      box-sizing: border-box;
      flex-shrink: 0;
      text-align: center;
    }

    .followup-content {
      flex: 1;
      border-left: 1px solid #f0f0f0;
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 16px 16px;
      box-sizing: border-box;

      /* 选项组：不随访/随访 */
      .visit-options {
        display: flex;
        align-items: center;
        gap: 12px;

        .visit-option {
          display: inline-flex;
          align-items: center;
          gap: 6px;
          padding: 6px 10px;
          border-radius: 6px;
          border: 1px solid transparent;
          cursor: pointer;
          color: #333;
          transition: all 0.15s ease-in-out;
          .icon-box {
            width: 18px;
            height: 18px;
            border-radius: 4px;
            background: #fff;
            border: 1px dashed #cfd4da; /* 未选中虚线框 */
            position: relative;
            flex-shrink: 0;
          }
        }
      }

      /* 医嘱事项输入，贴合行高且无强阴影 */
      .advice-input {
        width: 100%;
        :deep(.el-input__wrapper) {
          background: transparent;
          box-shadow: none;
          border: none;
          padding: 0;
          height: 36px;
        }
        :deep(input) {
          height: 36px;
        }
      }
    }
  }
}
.register-date-box {
  cursor: pointer;
  text-align: right;
}
.register-date-custom-picker {
  position: absolute;
  top: 100%;
  left: 0;
  z-index: 2000;
  margin-top: 4px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 8px 8px 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
}
</style>
